package dao;

import javax.persistence.criteria.CriteriaBuilder;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Section {
    public int sectionId;
    public String sectionName;
    public int cid;

    private static Connection connection=DBConnection.getDBCourseConnection();

    public static int insertInfo(String sectionName,int cid){
        int result=0;
        try {
            CallableStatement addCourse=connection.prepareCall("{call add_section(?,?,?)}");
            addCourse.setString(1,sectionName);
            addCourse.setInt(2,cid);
            addCourse.registerOutParameter(3, Types.INTEGER);
            addCourse.execute();
            result=addCourse.getInt(3);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static List<Integer> getSectionIdsByCid(int cid){
        String sql="select sectionId from section where cid=? order by sectionId asc";
        PreparedStatement preparedStatement=null;
        List<Integer> sectionIds=new ArrayList<>();
        try {
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setInt(1,cid);
            ResultSet resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                Integer i=resultSet.getInt(1);
                sectionIds.add(i);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sectionIds;
    }

    public static List<Section> getSectionsByCid(int cid){
        String sql="select * from section where cid=? order by sectionId asc";
        PreparedStatement preparedStatement=null;
        List<Section> sections=new ArrayList<>();
        try {
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setInt(1,cid);
            ResultSet resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                Section section=new Section();
                section.sectionId=resultSet.getInt(1);
                section.sectionName=resultSet.getString(2);
                section.cid=resultSet.getInt(3);
                sections.add(section);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sections;
    }

}
